package cn.fbs.service.core;

import cn.fbs.dao.dm.DMCodeCategoryTypeMapper;
import cn.fbs.dao.dm.DMQbCategoryConnectionMapper;
import cn.fbs.dao.dm.DMVideoInfoMapper;
import cn.fbs.model.TVideoInfo;
import cn.fbs.param.SearchParam;
import cn.fbs.param.VideoParam;
import cn.fbs.service.AssignService;
import cn.fbs.service.CategoryService;
import cn.fbs.vo.QueryVideoVo;
import cn.fbs.vo.TVideoInfoVo;
import cn.fbs.vo.TVideoItemVo;
import lombok.extern.java.Log;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Log
public class VideoService {
    @Value("${resource.locations}")
    private String resourceLocations;

    @Value(("${compressRatio}"))
    private Integer compressRatio;

    @Value(("${maxJoinNum}"))
    private int maxJoinNum;

    @Autowired
    private DMCodeCategoryTypeMapper categoryTypeMapper;

    @Autowired private CategoryService categoryService;

    @Autowired private DMQbCategoryConnectionMapper connectionMapper;

    @Autowired private DMVideoInfoMapper videoInfoMapper;

    @Autowired private AssignService assignService;

    public List<TVideoInfo> queryVideoByParam(QueryVideoVo videoVo) {
        return videoInfoMapper.queryVideoByParam(videoVo);

    }

    @Transactional(rollbackFor = Exception.class)
    public String updateZCVideo(VideoParam uploadParam) {
        String fileName = uploadParam.getFileName();
        if (fileName.endsWith("****")) {
            String bm = String.format("%04d", Integer.parseInt(categoryTypeMapper.getSequence()));
            String replace = fileName.replace("****", bm);
            uploadParam.setFileName(replace);
        }
        TVideoInfo videoInfo = new TVideoInfo();
        videoInfo.setUpdateDate(new Date());
        BeanUtils.copyProperties(uploadParam, videoInfo);
//        String fileName = generatorFileName(uploadParam.getCategoryIds(), uploadParam.getZzdx());
//        videoInfo.setFileName(fileName);
//        if (fileName.startsWith("500")) {
//            return fileName;
//        }
        File file = null;
        if (StringUtils.isNotBlank(uploadParam.getRealFileUrl())) {
            file = new File(uploadParam.getRealFileUrl());
        }
        if (file != null && file.exists()) {
            assignService.giveVideoInfo(uploadParam, videoInfo);
        }

        if (StringUtils.isNotBlank(videoInfo.getTargetType())) {
            if (videoInfoMapper.selectCountBytargetXh(videoInfo.getTargetType(), videoInfo.getId()) >= maxJoinNum) {
                return "400,目标关联数据超过最大限制!";
            }
        }
        videoInfoMapper.updateByPrimaryKeySelective(videoInfo);
        /**
         * 处理标签信息-删除原有标签，添加新标签
         */
        if (uploadParam.getCategoryIds() != null) {
            connectionMapper.deleteByMessageId(uploadParam.getId());
            if (uploadParam.getCategoryIds().size() > 0) {
                categoryService.insertCategory(uploadParam.getCategoryIds(), uploadParam.getOperator(), videoInfo.getId(), 3);
            }
        }
        return "200,操作成功";
    }

    public List<TVideoInfoVo> SearchVideo(SearchParam searchParam) {
        List<TVideoInfoVo> dataInfoVoList = new ArrayList<>();
        if (searchParam.getCategoryIds() == null) {
            dataInfoVoList = videoInfoMapper.searchVideoInfoVo(searchParam);
        } else {
            String categoryIdsStr = StringUtils.join(searchParam.getCategoryIds(), ",");
            /**
             * 先获取存在这些 标签ID的视频Id
             */
            List<Integer> messageIds = connectionMapper.getMessageIdByCategoryId(categoryIdsStr);
            /**
             * 查询这些id下的视频信息
             */
            if (messageIds != null && messageIds.size() > 0) {
                String idsStr = StringUtils.join(messageIds, ",");
                searchParam.setIdsStr(idsStr);
                dataInfoVoList = videoInfoMapper.selectVideoByIds(searchParam);
            }
        }
        return dataInfoVoList;
    }


    public TVideoItemVo getVideoItem(Integer id) {
        return videoInfoMapper.getVideoItem(id);
    }



    public String uploadVideo(VideoParam uploadParam) {
        String fileName = uploadParam.getFileName();
        if (fileName.endsWith("****")) {
            String bm = String.format("%04d", Integer.parseInt(categoryTypeMapper.getSequence()));
            String replace = fileName.replace("****", bm);
            uploadParam.setFileName(replace);
        }
        String realFileUrl = uploadParam.getRealFileUrl();
        if (StringUtils.isBlank(realFileUrl)) {
            return "500,文件地址无效";
        }
        if (!new File(realFileUrl).exists()) {
            return "500,文件地址无效";
        }

        if (StringUtils.isNotBlank(uploadParam.getTargetType())) {
            if (videoInfoMapper.selectCountBytargetXh(uploadParam.getTargetType(), 0L) >= maxJoinNum) {
                return "400,目标关联数据超过最大限制!";
            }
        }
//        String fileName = generatorFileName(uploadParam.getCategoryIds(), uploadParam.getZzdx());
//        if (fileName.startsWith("500")) {
//            return fileName;
//        }
//        uploadParam.setFileName(fileName);
        TVideoInfo videoInfo = insertVideoInfo(uploadParam);
//        insertAtlasMidT(uploadParam.getAtlasIds(),videoInfo.getId(),3);
        /**
         * 将关联的标签信息保存到关联表中
         */
        if (uploadParam.getCategoryIds() != null && uploadParam.getCategoryIds().size() > 0) {
            categoryService.insertCategory(uploadParam.getCategoryIds(), uploadParam.getOperator(), videoInfo.getId(), 3);
        }
        return "200,操作成功";
    }


    private TVideoInfo insertVideoInfo(VideoParam uploadParam) {
        TVideoInfo videoInfo = new TVideoInfo();
        BeanUtils.copyProperties(uploadParam, videoInfo);
        videoInfo.setFileName(uploadParam.getFileName());
        /**
         * 赋予媒体信息
         */
        assignService.giveVideoInfo(uploadParam, videoInfo);
        /**
         * 初始化信息
         */
        videoInfo.setCreateDate(new Date());
        videoInfo.setViewNumber(0L);
        videoInfo.setDownloads(0L);
//        videoInfo.setIsExamine(1);
        videoInfo.setId(null);
        videoInfoMapper.insertSelective(videoInfo);
        return videoInfo;
    }
}
